﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SHomeWorkshop.LunarConcept.ModifingManager;
using System.Windows;
using SHomeWorkshop.LunarConcept.Controls;
using System.Xml;
using SHomeWorkshop.LunarConcept.Tools;

namespace SHomeWorkshop.LunarConcept.Commands.TextCommands
{
    /// <summary>
    /// 创建时间：2012年2月20日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：提供自定义字符串命令的执行方法。
    ///           条件：⑴类名必须以“_TC”开头，否则会无法调用。
    ///                   类名即内置命令文本，用户输入的命令文本将被转换（通过映射表）成内置命令，
    ///                   根据内置命令字符串（即类名），找到类，并调用必须实现的下列方法：
    ///                 ⑵类必须实现带一个string型参数的:
    ///                   static string Execute(string parameters)方法，
    ///                   此方法必须自行处理parameters中以半角空格分隔的命令参数列表（当然，如果不需要，也可不处理）。
    /// </summary>
    [Tools.TextCommandAttribute("/i/nztb/tb/innericon/icon/图标/内置图标/", Enums.TextCommandType.Insert, "添加内置图标")]
    public class _TCInsertInnerIcon
    {
        /// <summary>
        /// [静态方法]
        /// </summary>
        /// <param name="parameters">字符串形式的参数列表（参数间用半角空格分隔）。</param>
        /// <returns>顺利执行返回string.Empty，否则返回错误信息字符串。</returns>
        public static string Execute(string parameters)
        {
            if (parameters != null && parameters.Trim() == "?")
            {
                TextCommandHelp.ShowHelp("_TCInsertInnerIcon");
                return string.Empty;
            }

            if (Globals.MainWindow == null) return "　　未找到主窗口。";

            LunarConcept.Controls.EditorManager manager = Globals.MainWindow.EditorManager;
            if (manager == null) return "　　未找到主窗口的页面管理器。";

            PageEditor mainPe = manager.GetMainSelectedPageEditor();
            if (mainPe == null) return "　　没有选定任何页面。";

            Widgets.Widget mainSel = mainPe.GetMainSelectedWidget();
            //if (mainSel == null) return "　　请先选定一个文本框或矩形。";
            // 2012年6月24日修改。现在如果mainSel为空，则直接在插入点位置添加图片框。

            char[] splitter = new char[1] { ' ' };
            string[] paras = parameters.Split(splitter, StringSplitOptions.RemoveEmptyEntries);

            if (paras.Length == 1)
            {
                if (mainSel != null)
                {
                    if (mainSel.RealRect.Left < 48) return "　　当前部件左侧没有足够空间放置内置图标。";
                }

                //不指定位置，默认在左侧并保持与当前部件垂直方向居中。
                //<Widget Type="PictureBox"/>
                string innerIconName = paras[0].ToLower();
                string xml = GetInnerIconPictureBoxXml(innerIconName);
                if (xml == null) return "　　不能识别的内置图标代号：" + innerIconName;

                Point? newLocation = null;
                if (mainSel != null)
                {
                    newLocation = GetNewLocation(mainSel.OuterRect, "");
                }
                else
                {
                    newLocation = mainPe.BaseInsertPoint;
                }
                if (newLocation == null) return "　　不能识别指定的位置。";

                ModifingInfo info = new ModifingInfo() { ModifingDescription = "　　插入内置图标。" };
                manager.GetSelectedPageEditorStatus(info);
                manager.GetSelectedWidgetStatus_Old(info);
                //manager.GetSelectedWidgetStatus_New(info);

                ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

                XmlNode widgetSetNode = mainPe.WidgetSetNode;

                if (widgetSetNode == null) return "　　发生意外，未找到当前页面的WidgetSet节点。";

                XmlNode newNode = widgetSetNode.AppendXmlAsChild(xml);
                Widgets.PictureBox pb = new Widgets.PictureBox(mainPe);
                pb.XmlData = newNode;
                pb.NewID();
                pb.Location = newLocation.Value;

                Action act = new Action(ActionType.WidgetAdded, mainPe.Id, pb.Id, null, pb.XmlData.OuterXml);
                mainPe.AddWidget(pb);

                if (mainSel == null)
                {
                    pb.IsMainSelected = true;
                    info.NewMainSelectedWidgetID = pb.Id;
                }

                mi.AddAction(act);
                manager.RegisterModifingItem(mi);
            }
            else if (paras.Length == 2)
            {
                string location = paras[0];
                string innerIconName = paras[1];
                string xml = GetInnerIconPictureBoxXml(innerIconName);
                if (xml == null) return "　　不能识别的内置图标代号：" + innerIconName;

                Point? newLocation = null;
                if (mainSel != null)
                {
                    newLocation = GetNewLocation(mainSel.OuterRect, location);
                }
                else
                {
                    newLocation = mainPe.BaseInsertPoint;
                }
                if (newLocation == null) return "　　不能识别指定的位置。";

                ModifingInfo info = new ModifingInfo() { ModifingDescription = "　　插入内置图标。" };
                manager.GetSelectedPageEditorStatus(info);
                manager.GetSelectedWidgetStatus_Old(info);
                //manager.GetSelectedWidgetStatus_New(info);

                ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

                XmlNode widgetSetNode = mainPe.WidgetSetNode;

                if (widgetSetNode == null) return "　　发生意外，未找到当前页面的WidgetSet节点。";

                XmlNode newNode = widgetSetNode.AppendXmlAsChild(xml);
                Widgets.PictureBox pb = new Widgets.PictureBox(mainPe);
                pb.XmlData = newNode;
                pb.NewID();
                pb.Location = newLocation.Value;

                Action act = new Action(ActionType.WidgetAdded, mainPe.Id, pb.Id, null, pb.XmlData.OuterXml);
                mainPe.AddWidget(pb);

                if (mainSel == null)
                {
                    pb.IsMainSelected = true;
                    info.NewMainSelectedWidgetID = pb.Id;
                }

                mi.AddAction(act);
                manager.RegisterModifingItem(mi);
            }
            if (paras.Length > 2) return "　　参数个数不正确。";

            return string.Empty;
        }

        private static Point? GetNewLocation(Rect srcRect, string location)
        {
            Point? newLocation;
            switch (location.ToLower())
            {
                case ""://默认左侧。
                case "left":
                case "l":
                case "z":
                case "左":
                    {
                        newLocation = new Point(srcRect.Left - 58,
                            srcRect.Top + srcRect.Height / 2 - 28);
                        break;
                    }
                case "right":
                case "r":
                case "y":
                case "右":
                    {
                        newLocation = new Point(srcRect.Right + 2,
                            srcRect.Top + srcRect.Height / 2 - 28);
                        break;
                    }
                case "up":
                case "u":
                case "s":
                case "上":
                    {
                        newLocation = new Point(srcRect.Left + srcRect.Width / 2 - 26,
                            srcRect.Top - 58);
                        break;
                    }
                case "down":
                case "d":
                case "x":
                case "下":
                    {
                        newLocation = new Point(srcRect.Left + srcRect.Width / 2 - 26,
                            srcRect.Bottom + 2);
                        break;
                    }
                case "lefttop":
                case "topLeft":
                case "lt":
                case "tl":
                case "zs":
                case "sz":
                case "左上":
                case "上左":
                    {
                        newLocation = new Point(srcRect.TopLeft.X + 3, srcRect.TopLeft.Y + 3); break;
                    }
                case "righttop":
                case "topright":
                case "tr":
                case "rt":
                case "sy":
                case "ys":
                case "右上":
                case "上右":
                    {
                        newLocation = new Point(srcRect.TopRight.X - 59, srcRect.Y + 3); break;
                    }
                case "bottomleft":
                case "leftbottom":
                case "lb":
                case "bl":
                case "zx":
                case "xz":
                case "左下":
                case "下左":
                    {
                        newLocation = new Point(srcRect.Left + 3, srcRect.Bottom - 59); break;
                    }
                case "bottomright":
                case "rightbottom":
                case "rb":
                case "br":
                case "yx":
                case "xy":
                case "右下":
                case "下右":
                    {
                        newLocation = new Point(srcRect.BottomRight.X - 59, srcRect.BottomRight.Y - 59);
                        break;
                    }
                default:
                    {
                        newLocation = null; break;
                    }
            }
            return newLocation;
        }

        private static string GetInnerIconPictureBoxXml(string innerIconName)
        {
            string xml = null;
            switch (innerIconName)
            {
                case "a":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"a\"/>"; break;
                    }
                case "b":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"b\"/>"; break;
                    }
                case "c":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"c\"/>"; break;
                    }
                case "d":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"d\"/>"; break;
                    }
                case "x":
                case "cw":
                case "ch":
                case "错误":
                case "叉号":
                case "错号":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"x\"/>"; break;
                    }
                case "arrow":
                case "jt":
                case ">":
                case "箭头":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"arrow\"/>"; break;
                    }
                case "question":
                case "？":
                case "？？":
                case "??":
                case "wh":
                case "问号":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"question\"/>"; break;
                    }
                case "right":
                case "dg":
                case "dh":
                case "gh":
                case "对勾":
                case "对号":
                case "勾号":
                    {
                        xml = "<Widget Type=\"PictureBox\" InnerIconName=\"right\"/>"; break;
                    }
                default:
                    {
                        return null;
                    }
            }

            return xml;
        }
    }
}
